import React, { useRef, useState, useEffect } from 'react';
import { Row, Col, Form, Input, Button } from 'antd';
import { compare } from 'src/utils/compare';
import FormItem from 'src/components/FormItem';

import { cloneDeep } from 'lodash';
import useRiskTypes from "../../../../hook/useRiskTypes";
import ActionsConfig from 'src/components/Actions/config';

const layout = {
  labelCol: {
    span: 6,
  },
  wrapperCol: {
    span: 18,
  },
};

function ActionNode(props) {
  const {
    name,
    disabled,
    compareData = {},
    value: xValue,
    actions,
    variable,
    isOld,
    isCompare,
    using_variables,
  } = props;
  const [value, setValue] = useState([]);

  const riskTypes = useRiskTypes();

  useEffect(() => {
    if (xValue && actions && actions.length > 0) {
      const values = createUsefullData(xValue);
      setValue(values);
    }
  }, [xValue, actions]);
  const _actionConfig = useRef(null);

  // 组装成前端可用的数据，将value和 函数数据进行组装，因为函数数据是引用
  function createUsefullData(value) {
    const temp = cloneDeep(value);
    return temp.map((item) => {
      const cur = cloneDeep(actions.find((it) => it.code === item.code));
      if (cur) {
        cur.parameters =
          cur.parameters &&
          cur.parameters.map((param, index) => {
            const itemParam = (item.parameters && item.parameters[index]) || {};
            if (
              Object.keys(itemParam.value).length &&
              itemParam.value.var_code &&
              typeof itemParam.value.var_code === 'string' &&
              itemParam.value.var_code.includes(',')
            ) {
              itemParam.value.var_code = itemParam.value.var_code.split(',');
            }
            return {
              ...param,
              ...itemParam,
            };
          });
      }
      return cur;
    });
  }
  const handleSubmit = (e) => {
    e.preventDefault();
    props.form.validateFields((err, values) => {
      if (!err) {
        _actionConfig.current.getValue((value, error) => {
          if (!error) {
            const newValue = value.map((item) => {
              item.parameters = item.parameters.map(({ value }) => {
                const temp = { ...value };
                if (Array.isArray(temp.var_code)) {
                  temp.var_code = temp.var_code.join(',');
                }
                return { value: temp };
              });
              return item;
            });
            const params = { name: values.name };
            if (props.sourceId) {
              params.sourceId = props.sourceId;
            }
            props.onSubmit && props.onSubmit({ actions: newValue, ...params });
          }
        });
      }
    });
  };
  const formItems = [
    {
      label: {
        label: '节点名称',
        ...layout,
      },
      name: 'name',
      options: {
        initialValue: name,
        rules: [
          { required: true, message: '请输入节点名称' },
          { pattern: /^[\u4E00-\u9FA5_a-zA-Z0-9]+$/, message: '限中英文数字下划线' },
          { max: 128, message: '最长128个字符' },
        ],
      },
      component: (
        <Input
          placeholder='请填写节点名称'
          disabled={disabled}
          style={compare({ ...props, value: { name } }, 'name')}
        />
      ),
    },
  ];
  return (
    <div className='stretegy-wp'>
      <Form onSubmit={() => false} className='stretegy-wp-form'>
        <Row type='flex' gutter={20}>
          {formItems.map((item) => {
            return (
              <Col span={12} key={item.name}>
                <FormItem form={props.form} item={item} colNum={1} />
              </Col>
            );
          })}
        </Row>
        <ActionsConfig
          {...props}
          isCompare={isCompare}
          isOld={isOld}
          variable={variable}
          using_variables={using_variables}
          value={value}
          name={name}
          createRef={_actionConfig}
          disabled={disabled}
          compareData={compareData.actions && createUsefullData(compareData.actions)}
          actions={actions}
          riskTypes={riskTypes}
        />
        {!disabled && (
          <Row type='flex' justify='start' className='form-submit-area form-submit-area2'>
            <Col>
              <Button type='primary' onClick={handleSubmit} autoFocus={true}>
                确定
              </Button>
              <Button style={{ marginLeft: '15px' }} onClick={() => props.close && props.close()}>
                取消
              </Button>
            </Col>
          </Row>
        )}
      </Form>
    </div>
  );
}

export default Form.create()(ActionNode);
